<template>
    <button
        class="upload-avatar-btn"
        :style="styles"
        hover-class="none"
        open-type="chooseAvatar"
        @click="chooseAvatar"
        @chooseavatar="chooseAvatar"
    >
        <u-icon class="img-fix" color="#eee" size="28" name="camera"></u-icon>
        <image class="w-full h-full" mode="heightFix" :src="modelValue" />
    </button>
</template>
<script lang="ts" setup>
import { computed } from "vue";
import { messageSuccess } from "@/utils/message";
import { uplaodImage } from "@/api/upload";
import { updateAvatar } from "@/api/user";

const props = defineProps({
    modelValue: {
        type: String,
    },
    size: {
        type: [String, Number],
        default: 120,
    },
});

const emit = defineEmits<{
    (event: "update:modelValue", value: string): void;
}>();

const styles = computed(() => {
    return {
        width: props.size + "rpx",
        height: props.size + "rpx",
        borderRadius: "50%",
    };
});

const chooseAvatar = async (e: any) => {
    // #ifdef MP-WEIXIN
    if (e.detail?.avatarUrl) return;
    uni.showLoading({ title: "上传中..." });

    try {
        const res = await uplaodImage(e.detail?.avatarUrl);
        await updateAvatar({ avatar: res["url"] });
        uni.hideLoading();
        messageSuccess("修改成功");
        emit("update:modelValue", res["uri"]);
    } catch (e) {
        uni.hideLoading();
        return;
    }
    // #endif

    // #ifndef MP-WEIXIN
    uni.chooseImage({
        success: async (chooseImageRes) => {
            uni.showLoading({ title: "上传中..." });
            const tempFilePaths = chooseImageRes.tempFilePaths;

            try {
                const res = await uplaodImage(tempFilePaths[0]);
                await updateAvatar({ avatar: res["url"] });
                uni.hideLoading();
                messageSuccess("修改成功");
                emit("update:modelValue", res["uri"]);
            } catch (e) {
                uni.hideLoading();
                return;
            }
        },
    });
    // #endif
};
</script>

<style lang="scss" scoped>
.upload-avatar-btn {
    background-color: #fff;
    overflow: hidden;
    padding: 0;
    margin: 0;
    border-radius: 50%;
    &::after {
        border: none;
    }

    &:before {
        content: "";
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.3);
        pointer-events: none;
        z-index: 1000;
    }

    .img-fix {
        position: absolute;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 1001;
    }
}
</style>
